<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="60%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <!-- 第一组：基本信息 -->
      <el-card class="mb-20px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="委托单位" prop="companyName">
              <el-input
                v-model="formData.companyName"
                :class="['customer-input']"
                placeholder="双击选择委托单位"
                readonly
                @dblclick="handleCompanyNameDblClick"
              >
                <template #append>
                  <el-tooltip content="双击输入框选择委托单位" effect="dark" placement="top">
                    <Icon icon="ep:info-filled" />
                  </el-tooltip>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目类型" prop="projectType">
              <el-tree-select
                v-model="formData.projectType"
                :data="projectTypeOptions"
                :props="{
                  value: 'id',
                  label: 'name',
                  children: 'children'
                }"
                placeholder="请选择项目类型"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目负责人" prop="projectManagerId">
              <el-input
                v-model="formData.projectManagerName"
                placeholder="双击选择项目负责人"
                readonly
                @dblclick="handleProjectManagerDblClick"
                :class="['customer-input']"
              >
                <template #append>
                  <el-tooltip content="双击输入框选择项目负责人" effect="dark" placement="top">
                    <Icon icon="ep:info-filled" />
                  </el-tooltip>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="紧急程度" prop="urgencyLevel">
              <el-select v-model="formData.urgencyLevel" placeholder="请选择紧急程度">
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.URGENCY_DEGREE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 第二组：受检信息 -->
      <el-card class="mb-20px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="受检单位" prop="receivingUnit">
              <el-input v-model="formData.receivingUnit" placeholder="请输入受检单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="受检地址" prop="receivingAddress">
              <el-input v-model="formData.receivingAddress" placeholder="请输入受检地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位联系人" prop="contactPerson">
              <el-input v-model="formData.contactPerson" placeholder="请输入单位联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="受检电话" prop="contactPhone">
              <el-input v-model="formData.contactPhone" placeholder="请输入受检电话" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 第三组：业务信息 -->
      <el-card>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="合同编号" prop="contractNo">
              <el-input v-model="formData.contractNo" placeholder="请输入合同编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报告编号" prop="reportNo">
              <el-input v-model="formData.reportNo" placeholder="请输入报告编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务编号" prop="taskNo">
              <el-input v-model="formData.taskNo" placeholder="请任务编号编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目编号" prop="projectNo">
              <el-input v-model="formData.projectNo" placeholder="请输入项目编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="formData.projectName" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务员" prop="businessPerson">
              <el-input v-model="formData.businessPerson" placeholder="请输入业务员" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务电话" prop="businessPhone">
              <el-input v-model="formData.businessPhone" placeholder="请输入业务电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同日期" prop="contractDate">
              <el-date-picker
                v-model="formData.contractDate"
                placeholder="选择合同日期"
                style="width: 100%"
                type="date"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input
                v-model="formData.remarks"
                :rows="3"
                placeholder="请输入备注"
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- 添加客户选择对话框 -->
  <el-dialog v-model="customerDialogVisible" append-to-body title="选择客户" width="80%">
    <CustomerList @select="handleCustomerSelect" />
  </el-dialog>

  <!-- 修改项目负责人选择对话框 -->
  <el-dialog v-model="userDialogVisible" append-to-body title="选择项目负责人" width="80%">
    <SystemUser :selectable="true" @select="handleUserSelect" />
  </el-dialog>
</template>
<script setup lang="ts">
import { ProjectApi, ProjectVO } from '@/api/dk/project'
import * as UserApi from '@/api/system/user'
import CustomerList from '@/views/dk/customer/index.vue'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import SystemUser from '@/views/system/user/index.vue'

/** 项目 表单 */
defineOptions({ name: 'ProjectForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  companyName: undefined,
  projectType: undefined as number | undefined,
    projectManagerId: undefined as number | undefined,
    projectManagerName: undefined as string | undefined,
  urgencyLevel: '1',
  completionDate: undefined,
  receivingUnit: undefined,
  receivingAddress: undefined,
  contactPerson: undefined,
  contactPhone: undefined,
  taskSource: undefined,
  contractNo: undefined,
  projectNo: undefined,
  reportNo: undefined,
  numberPrefix: undefined,
  taskNo: undefined,
  projectName: undefined,
  businessPerson: undefined,
  businessPhone: undefined,
  contractDate: undefined as string | undefined,
  remarks: undefined,
  day: undefined
})
const formRules = reactive({
  companyName: [{ required: true, message: '委托单位名称不能为空', trigger: '' }],
  projectType: [{ required: true, message: '项目类型不能为空', trigger: '' }],
  projectManagerId: [{ required: true, message: '项目负责人不能为空', trigger: '' }],
  urgencyLevel: [{ required: true, message: '紧急程度不能为空', trigger: '' }],
  receivingUnit: [{ required: true, message: '受检单位不能为空', trigger: '' }],
  receivingAddress: [{ required: true, message: '受检地址不能为空', trigger: '' }],
  contactPerson: [{ required: true, message: '单位联系人不能为空', trigger: '' }],
  contactPhone: [{ required: true, message: '受检电话不能为空', trigger: '' }],
  contractNo: [{ required: true, message: '合同编号不能为空', trigger: '' }],
  reportNo: [{ required: true, message: '报告编号不能为空', trigger: '' }],
  taskNo: [{ required: true, message: '任务编号不能为空', trigger: '' }],
  projectNo: [{ required: true, message: '项目编号不能为空', trigger: '' }]
})
const formRef = ref() // 表单 Ref

// 项目类型选项
const projectTypeOptions = ref([])

// 获取项目类型树形数据
const getProjectTypeTree = async () => {
  try {
    // 获取树形数据，type=1
    const data = await ProjectApi.getMaterialClassList(1)
    // 转换成树形结构
    projectTypeOptions.value = formatTreeData(data)
  } catch (error) {
    console.error('获取项目类型失败:', error)
  }
}

// 将扁平数据转换为树形结构
const formatTreeData = (data: any[]): any[] => {
  const map = new Map()
  const result: any[] = []

  // 先用Map存储所有节点
  data.forEach((item) => {
    map.set(item.id, { ...item, children: [] })
  })

  // 构建树形结构
  data.forEach((item) => {
    const node = map.get(item.id)
    if (item.parentId === 0) {
      result.push(node)
    } else {
      const parent = map.get(item.parentId)
      if (parent) {
        parent.children.push(node)
      }
    }
  })

  return result
}

/** 打开弹窗 */
const open = async (type: string, id?: number, customerInfo?: any) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '新增项目' : '编辑项目'
  formType.value = type
  resetForm()

  // 获取项目类型数据
  await getProjectTypeTree()

  // 修改时，先获取数据
  if (id) {
    formLoading.value = true
    try {
      const projectData = await ProjectApi.getProject(id)
      // 确保项目类型是数字类型
      formData.value = {
        ...projectData,
        projectType: Number(projectData.projectType)
      }
      // 负责人：保存ID，显示昵称
      if (projectData.projectManager) {
        try {
          const pmInfo = await UserApi.getUser(Number(projectData.projectManager))
          formData.value.projectManagerId = Number(projectData.projectManager)
          formData.value.projectManagerName = pmInfo.nickname
        } catch (error) {
          console.error('获取项目负责人信息失败:', error)
        }
      }
    } finally {
      formLoading.value = false
    }
    return
  }

  // 如果是新增，设置默认项目类型和客户信息
  if (type === 'create') {
    formData.value.projectType = 179
    formData.value.urgencyLevel = '1'
    // 如果传入了客户信息，则设置相关字段
    if (customerInfo) {
      formData.value.companyName = customerInfo.companyName
      formData.value.contactPerson = customerInfo.contactPerson
      formData.value.contactPhone = customerInfo.contactPhone
      formData.value.receivingUnit = customerInfo.receivingUnit
      formData.value.receivingAddress = customerInfo.receivingAddress
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ProjectVO
    if (formType.value === 'create') {
      // 提交前将负责人ID映射到后端字段
      ;(data as any).projectManager = (formData.value as any).projectManagerId
      delete (data as any).projectManagerName
      delete (data as any).projectManagerId
      await ProjectApi.createProject(data)
      message.success(t('common.createSuccess'))
    } else {
      ;(data as any).projectManager = (formData.value as any).projectManagerId
      delete (data as any).projectManagerName
      delete (data as any).projectManagerId
      await ProjectApi.updateProject(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    companyName: undefined,
    projectType: undefined as number | undefined,
    projectManagerId: undefined as number | undefined,
    projectManagerName: undefined as string | undefined,
    urgencyLevel: '1',
    completionDate: undefined,
    receivingUnit: undefined,
    receivingAddress: undefined,
    contactPerson: undefined,
    contactPhone: undefined,
    taskSource: undefined,
    contractNo: undefined,
    projectNo: undefined,
    projectName: undefined,
    businessPerson: undefined,
    businessPhone: undefined,
    contractDate: undefined as string | undefined,
    remarks: undefined,
    day: undefined
  }
  formRef.value?.resetFields()
}

const customerDialogVisible = ref(false) // 客户选择弹窗显示状态

// 双击委托单位名称输入框处理函数
const handleCompanyNameDblClick = () => {
  customerDialogVisible.value = true
}

// 选择客户后的回调函数
const handleCustomerSelect = (customer: any) => {
  formData.value.companyName = customer.name // 设置委托单位名称
  formData.value.contactPerson = customer.contactPerson // 设置联系人
  formData.value.contactPhone = customer.contactPhone // 设置联系电话
  formData.value.receivingUnit = customer.name // 设置受检单位
  formData.value.receivingAddress = customer.address // 设置受检地址
  customerDialogVisible.value = false
}

// 添加用户选择相关的状态
const userDialogVisible = ref(false) // 用户选择弹窗显示状态

// 双击项目负责人输入框处理函数
const handleProjectManagerDblClick = () => {
  userDialogVisible.value = true
}

// 修改选择用户后的回调函数
const handleUserSelect = (user: any) => {
  formData.value.projectManagerId = (user && (user.id ?? user.userId)) as number | undefined
  formData.value.projectManagerName = user.nickname // 设置项目负责人显示昵称
  userDialogVisible.value = false
}

// 监听项目类型选择变化
watch(
  () => formData.value.projectType,
  async (newProjectType) => {
    if (newProjectType) {
      // 从项目类型选项中找到对应的数据
      const findProjectType = (list: any[]): any => {
        for (const item of list) {
          if (item.id === newProjectType) {
            return item
          }
          if (item.children?.length) {
            const found = findProjectType(item.children)
            if (found) return found
          }
        }
        return null
      }

      const selectedType = findProjectType(projectTypeOptions.value)
      if (selectedType) {
        formData.value.day = selectedType.day // 设置 day 值
      }
    }
  }
)
</script>

<style scoped>
.customer-input :deep(.el-input__wrapper) {
  cursor: pointer;
  background-color: var(--el-fill-color-light);
}

.customer-input :deep(.el-input__inner) {
  cursor: pointer;
}

.mb-20px {
  margin-bottom: 20px;
}

:deep(.el-card__body) {
  padding: 16px;
}
</style>
